package server;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;

import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;



public class Session {
	private SSLSocket socket;
	private String subject;
	private int PORT;
	public Session(int PORT){
		this.PORT = PORT;
	
}

	public Session doIt(){
		try{
		// Create/initialize the SSLContext with key material
		char[] passphrase = "keystore".toCharArray();
		char[] keysPass = "storepass".toCharArray();
		// First initialize the key and trust material.	
		KeyStore ksKeys = KeyStore.getInstance("JKS");
		KeyStore ksTrust = KeyStore.getInstance("JKS");
		ksTrust.load(new FileInputStream("certificates/test/server.jks"), passphrase);		
		
		File f = new File("certificates/test/");					
		String[] fileList = f.list();
        for (int i = 0; i < fileList.length; i++){
        	if(fileList[i].endsWith(".jks") && !fileList[i].startsWith("server")){
        		ksKeys.load(new FileInputStream("certificates/test/"+fileList[i]), keysPass);        		
        	}        		
        }
		
		
		// TrustManager's decide whether to allow connections.
		TrustManagerFactory tmf =
		    TrustManagerFactory.getInstance("SunX509");
		tmf.init(ksTrust);
		
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(ksKeys, passphrase);
		
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(
		    kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

		SSLServerSocket serverSocket =  
			(SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(PORT);
	
		
		socket = (SSLSocket)serverSocket.accept();
		socket.setNeedClientAuth(true);
		
		socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {			
			@Override
			public void handshakeCompleted(HandshakeCompletedEvent event) {
				System.out.println("Handshake completed");		
			}
		});
		
		
		System.out.println("Connect!");
		
		SSLSession session = socket.getSession();
		
		Certificate[] serverCerts = session.getPeerCertificates();
		System.out.println("Retreived Server's Certificate Chain");
		javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0];
		subject = cert.getSubjectDN().getName();
		}catch(Exception e){
			
		}
		return this;
	}
	public SSLSocket getSocket() {
		return socket;
	}
	
	public String getSubject(){
		return subject;
	}
	

}
